package com.smartEdu.handler.redis;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RedisInfo {
	private Map<String, String> map = null;

	public RedisInfo(String info) {
		this(parse(info));
	}

	protected static Map<String, String> parse(String info) {
		String regex = "(.*?):(.+)";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(info);
		Map<String, String> map = new LinkedHashMap<String, String>();
		while (m.find()) {
			String key = m.group(1);
			String value = m.group(2);
			map.put(key, value);
		}
		return map;
	}

	public RedisInfo(Map<String, String> map) {
		this.map = map;
	}

	public long getUsedMemory() {
		return Long.parseLong(map.get("used_memory"));
	}

	public String getUsedMemoryHuman() {
		return map.get("used_memory_human");
	}

	public int getKeyCount() {
		String dbinfo = map.get("db0").trim();
		return getKeyCount(dbinfo);
	}

	protected int getKeyCount(String dbinfo) {
		String regex = "keys=([0-9]+),";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(dbinfo);
		if (m.find()) {
			return Integer.parseInt(m.group(1));
		} else {
			return -1;
		}
	}

	public int getExpiredKeys() {
		return Integer.parseInt(map.get("expired_keys"));
	}

	public int getEvictedKeys() {
		return Integer.parseInt(map.get("evicted_keys"));
	}

	public float getUsedCpuUser() {
		return Float.parseFloat(map.get("used_cpu_user"));
	}

	public float getUsedCpuSys() {
		return Float.parseFloat(map.get("used_cpu_sys"));
	}

	@Override
	public String toString() {
		return map.toString();
	}

}
